package com.qzsoft.system.modules.permission.deptJob.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qzsoft.jeemis.common.annotation.LogOperation;
import com.qzsoft.jeemis.common.constant.Constant;
import com.qzsoft.jeemis.common.utils.Result;
import com.qzsoft.jeemis.common.validator.AssertUtils;
import com.qzsoft.jeemis.common.validator.ValidatorUtils;
import com.qzsoft.jeemis.common.validator.group.AddGroup;
import com.qzsoft.jeemis.common.validator.group.DefaultGroup;
import com.qzsoft.jeemis.common.validator.group.UpdateGroup;
import com.qzsoft.system.modules.permission.dept.dao.SysDeptMapper;
import com.qzsoft.system.modules.permission.deptJob.dao.SysDeptJobMapper;
import com.qzsoft.system.modules.permission.deptJob.dto.SysDeptJobDTO;
import com.qzsoft.system.repository.sys.dao.SysDeptDao;
import com.qzsoft.system.repository.sys.entity.SysDeptEntity;
import com.qzsoft.system.repository.sys.entity.SysDeptJobEntity;
import com.qzsoft.system.modules.permission.deptJob.service.SysDeptJobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (SysDeptJob)表控制层
 *
 * @author yzz
 * @since 2020-07-30 09:42:39
 */
@RestController
@RequestMapping("/sys/sysdeptjob")
@Api(tags = "")
@Log4j2
public class SysDeptJobController {
    @Autowired
    private SysDeptJobService sysDeptJobService;
    @Autowired
    SysDeptJobMapper jobMapper;
    @Autowired
    SysDeptDao sysDeptDao;
    @Autowired
    SysDeptMapper deptMapper;



    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = "title", value = "标题", paramType = "query", dataType="String")
    })
    @RequiresPermissions("demo:sysdeptjob:page")
    public Result<IPage<SysDeptJobDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        IPage<SysDeptJobDTO> page = sysDeptJobService.page(params);

        return new Result<IPage<SysDeptJobDTO>>().ok(page);
    }

    @GetMapping("list")
    @ApiOperation("列表")
    @RequiresPermissions("demo:sysdeptjob:list")
    public Result<List<SysDeptJobDTO>> list(@ApiIgnore @RequestParam Map<String, Object> params){
        List<SysDeptJobDTO> data = sysDeptJobService.list(params);

        return new Result<List<SysDeptJobDTO>>().ok(data);
    }

    @GetMapping("moveTo")
    @ApiOperation("列表")
    @RequiresPermissions("demo:sysdeptjob:save")
    public Result<List<SysDeptJobDTO>> moveTo(@ApiIgnore @RequestParam Map<String, Object> params){
        sysDeptJobService.moveTo(params);

        return new Result();
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("demo:sysdeptjob:info")
    public Result<SysDeptJobEntity> get(@PathVariable("id") String id){
        SysDeptJobEntity data = sysDeptJobService.get(id);

        return new Result<SysDeptJobEntity>().ok(data);
    }

    @PostMapping("save")
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("demo:sysdeptjob:save")
    public Result save(@RequestBody SysDeptJobEntity entity){
        //效验数据
        ValidatorUtils.validateEntity(entity, AddGroup.class, DefaultGroup.class);
        sysDeptJobService.save(entity);
        return new Result();
    }

    @PostMapping("batchsave")
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("demo:sysdeptjob:save")
    public Result batchsSave(@RequestBody List<SysDeptJobEntity> list){
        //效验数据
        ValidatorUtils.validateEntity(list, AddGroup.class, DefaultGroup.class);
        sysDeptJobService.batchSave(list);
        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("demo:sysdeptjob:update")
    public Result update(@RequestBody SysDeptJobEntity dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        sysDeptJobService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("demo:sysdeptjob:delete")
    public Result delete(@RequestBody String[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        sysDeptJobService.delete(ids);

        return new Result();
    }



    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("demo:sysdeptjob:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params , HttpServletResponse response) throws Exception {
        sysDeptJobService.exportXls(params,response);
    }

    @GetMapping("chooseDeptJob")
    @ApiOperation("列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jobname", value = "岗位名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "code", value = "组织机构code", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "flag", value = "是否是按照名称模糊查询", paramType = "query", dataType = "String")
    })
    public Result<List<Map<String,Object>>>   chooseDeptJob(String jobName,String code,String flag) throws IllegalAccessException {
        QueryWrapper<SysDeptEntity> query=new QueryWrapper<>();
        query.eq("pid",code).orderByAsc("sort");

        List<SysDeptEntity> entityList = sysDeptDao.selectList(query);
        Map<String,Object>  paras=new HashMap<String,Object>();

        List<Map<String,Object>> result=new ArrayList<Map<String,Object>>();
        QueryWrapper<SysDeptJobEntity> jobquery=new QueryWrapper<>();
        jobquery.groupBy("dept_code");
        jobquery.select("dept_code,count(1) as count ");
        List<Map<String, Object>>  jobCountList=jobMapper.selectMaps(jobquery);
        int count=0;

        if(flag.equals("1")) {
            //添加组织信息
            for (SysDeptEntity deptEntity : entityList) {
                //获取岗位数量信息
                for (Map<String, Object> jobtmap:jobCountList) {
                    if(jobtmap.get("dept_code").equals(deptEntity.getId())){
                        count= ((Long)jobtmap.get("count")).intValue();
                    }
                }

                //添加组织详细信息
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", deptEntity.getId());
                map.put("name", deptEntity.getName());
                map.put("realName", null);
                map.put("checked", false);
                map.put("hasDept", deptEntity.getHasLeaf().equals("0") ? true : false);
                map.put("count",count);
                map.put("headUrl", null);
                map.put("isDept", true);
                result.add(map);
            }
        }

        //添加岗位信息信息
        if(!StringUtils.isBlank(jobName)||!StringUtils.isBlank(code)){
            jobquery=new QueryWrapper<>();
            if(!StringUtils.isBlank(jobName)){
                jobquery.like("job_name",jobName);
            }
            if(!StringUtils.isBlank(code)){
                jobquery.eq("dept_code",code).orderByAsc("sort");
            }
            List<Map<String,Object>> jobList=jobMapper.selectMaps(jobquery);
            for (Map<String,Object> jobMap:jobList) {
                jobMap.put("hasDept",false);
                jobMap.put("headUrl",null);
                jobMap.put("isDept",false);
                jobMap.put("count",0);
                jobMap.put("checked",false);
                jobMap.put("name",jobMap.get("job_name"));
                result.add(jobMap);
            }
        }


        return new Result<List<Map<String,Object>>>().ok(result);
    }

}